package com.yupi.soulba.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.soulba.common.BaseResponse;
import com.yupi.soulba.common.ErrorCode;
import com.yupi.soulba.common.ResultUtils;
import com.yupi.soulba.exception.BusinessException;
import com.yupi.soulba.mapper.TeamMapper;
import com.yupi.soulba.mapper.UserMapper;
import com.yupi.soulba.model.domain.Team;
import com.yupi.soulba.model.domain.User;
import com.yupi.soulba.model.domain.UserTeam;
import com.yupi.soulba.model.dto.TeamQuery;
import com.yupi.soulba.model.request.*;
import com.yupi.soulba.model.vo.TeamUserVo;
import com.yupi.soulba.service.TeamService;
import com.yupi.soulba.service.UserService;
import com.yupi.soulba.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 *
 * @author 黄云杰、过江辉
 */
@RestController
@RequestMapping("/team")

@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;
    
    @Resource
    private UserTeamService userTeamService;
    
    @Resource
    private TeamMapper teamMapper;

    /**
     * 新增队伍
     * @param teamAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    /**
     * 解散队伍
     * @param teamDisbandRequest
     * @param request
     * @return
     */
    @PostMapping("/disband")
    public BaseResponse<Boolean> disbandTeam(@RequestBody TeamDisbandRequest teamDisbandRequest, HttpServletRequest request) {
        if(teamDisbandRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean disbandResult = teamService.disbandTeam(teamDisbandRequest, loginUser);
        return ResultUtils.success(disbandResult);
    }

    /**
     * 更新队伍信息
     * @param teamUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request){
        if(teamUpdateRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
        if(!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取队伍信息
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id) {
        if(id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if(team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    /**
     * 获取队伍列表（公开 or 加密）
     * @param teamQuery
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVo>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无查询参数");
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、查询用户队伍列表
        List<TeamUserVo> teamUserVoList = teamService.listTeams(teamQuery, isAdmin);
        final List<Long> teamUserVoIdList = teamUserVoList
                .stream()
                .map(TeamUserVo::getId)
                .collect(Collectors.toList());
        // 2、判断用户是否已经加入队伍（前端判断 "加入队伍" 显隐）
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamUserVoIdList);
            // 已加入的队伍列表
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍id集合
            Set<Long> hasJoinTeamIdSet = userTeamList
                    .stream()
                    .map(UserTeam::getTeamId)
                    .collect(Collectors.toSet());
            teamUserVoList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e){}
        // 3、查询每个队伍的已加入用户数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamUserVoIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 一条或多条用户队伍列表（即该队伍已加入用户数）
        Map<Long, List<UserTeam>> groupByTeamIdUserTeamMap = userTeamList
                .stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 依次获得并赋值
        teamUserVoList.forEach(team -> {
            int hasJoinNum = groupByTeamIdUserTeamMap
                    .getOrDefault(team.getId(), new ArrayList<>()).size();
            team.setHasJoinNum(hasJoinNum);
        });
        return ResultUtils.success(teamUserVoList);
    }

    /**
     * 获取队伍列表（公开 and 加密）
     * @param searchKeyText
     * @return
     */
    @GetMapping("/list/search")
    public BaseResponse<List<TeamUserVo>> listTeamsSearchTeam(@RequestParam(required = false) String searchKeyText, HttpServletRequest request) {
        if (searchKeyText == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无查询参数");
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、查询用户队伍列表
        List<TeamUserVo> teamUserVoList = teamService.listTeamsSearchTeam(searchKeyText, isAdmin);
        final List<Long> teamUserVoIdList = teamUserVoList
                .stream()
                .map(TeamUserVo::getId)
                .collect(Collectors.toList());
        // 2、判断用户是否已经加入队伍（前端判断 "加入队伍" 显隐）
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamUserVoIdList);
            // 已加入的队伍列表
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍id集合
            Set<Long> hasJoinTeamIdSet = userTeamList
                    .stream()
                    .map(UserTeam::getTeamId)
                    .collect(Collectors.toSet());
            teamUserVoList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e){}
        // 3、查询每个队伍的已加入用户数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamUserVoIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 一条或多条用户队伍列表（即该队伍已加入用户数）
        Map<Long, List<UserTeam>> groupByTeamIdUserTeamMap = userTeamList
                .stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 依次获得并赋值
        teamUserVoList.forEach(team -> {
            int hasJoinNum = groupByTeamIdUserTeamMap
                    .getOrDefault(team.getId(), new ArrayList<>()).size();
            team.setHasJoinNum(hasJoinNum);
        });
        return ResultUtils.success(teamUserVoList);
    }

    // todo 优化查询分页
    /**
     * 分页获取队伍列表
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamsByPage(TeamQuery teamQuery) {
        if(teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(team, teamQuery);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> reaultPage = teamService.page(page, queryWrapper);
        if(reaultPage == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(reaultPage);
    }

    /**
     * 加入队伍
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if(teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean joinResult = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(joinResult);
    }

    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if(teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean quitResult = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(quitResult);
    }

    /**
     * 获取当前用户为队长的队伍列表
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/my/lead")
    public BaseResponse<List<TeamUserVo>> listMyLeadTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无查询参数");
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVo> teamUserVoList = teamService.listTeams(teamQuery, true);
        final List<Long> teamUserVoIdList = teamUserVoList
                .stream()
                .map(TeamUserVo::getId)
                .collect(Collectors.toList());
        // 2、判断用户是否已经加入队伍（前端判断 "加入队伍" 显隐）
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamUserVoIdList);
            // 已加入的队伍列表
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍id集合
            Set<Long> hasJoinTeamIdSet = userTeamList
                    .stream()
                    .map(UserTeam::getTeamId)
                    .collect(Collectors.toSet());
            teamUserVoList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e){}
        // 查询每个队伍的已加入用户数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamUserVoIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 一条或多条用户队伍列表（即该队伍已加入用户数）
        Map<Long, List<UserTeam>> groupByTeamIdUserTeamMap = userTeamList
                .stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 依次获得并赋值
        teamUserVoList.forEach(team -> {
            int hasJoinNum = groupByTeamIdUserTeamMap
                    .getOrDefault(team.getId(), new ArrayList<>()).size();
            team.setHasJoinNum(hasJoinNum);
        });
        return ResultUtils.success(teamUserVoList);
    }

    /**
     * 获取当前用户加入的队伍列表
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVo>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无查询参数");
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的 teamIdList
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> teamIdList = new ArrayList<>(listMap.keySet());
        List<TeamUserVo> teamUserVoList = new ArrayList<>();
        // 因为listTeams方法如果查询条件为空,默认查询所有队伍 
        // listMyJoinTeams方法需要没有加入队伍时显示数据为空
        // 所以直接返回空集合 避免查询所有队伍
        if(CollectionUtils.isEmpty(teamIdList)) {
            teamUserVoList.clear();
            return ResultUtils.success(teamUserVoList);
        }
        teamQuery.setIdList(teamIdList);
        teamUserVoList = teamService.listTeams(teamQuery, true);
        final List<Long> teamUserVoIdList = teamUserVoList
                .stream()
                .map(TeamUserVo::getId)
                .collect(Collectors.toList());
        // 2、判断用户是否已经加入队伍（前端判断 "加入队伍" 显隐）
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamUserVoIdList);
            // 已加入的队伍列表
            userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍id集合
            Set<Long> hasJoinTeamIdSet = userTeamList
                    .stream()
                    .map(UserTeam::getTeamId)
                    .collect(Collectors.toSet());
            teamUserVoList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e){}
        // 查询每个队伍的已加入用户数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamUserVoIdList);
        userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 一条或多条用户队伍列表（即该队伍已加入用户数）
        Map<Long, List<UserTeam>> groupByTeamIdUserTeamMap = userTeamList
                .stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 依次获得并赋值
        teamUserVoList.forEach(team -> {
            int hasJoinNum = groupByTeamIdUserTeamMap
                    .getOrDefault(team.getId(), new ArrayList<>()).size();
            team.setHasJoinNum(hasJoinNum);
        });
        return ResultUtils.success(teamUserVoList);
    }

    /**
     * 根据用户id查询其加入的队伍列表
     * @param userId
     * @return
     */
    @GetMapping("/list/user/join")
    public BaseResponse<List<TeamUserVo>> listUserJoinTeams(@RequestParam(required = false) Long userId, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的 teamIdList
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> teamIdList = new ArrayList<>(listMap.keySet());
        List<TeamUserVo> teamUserVoList = new ArrayList<>();
        // 因为listTeams方法如果查询条件为空,默认查询所有队伍 
        // listUserJoinTeams方法需要没有加入队伍时显示数据为空
        // 所以直接返回空集合 避免查询所有队伍
        if(CollectionUtils.isEmpty(teamIdList)) {
            teamUserVoList.clear();
            return ResultUtils.success(teamUserVoList);
        }
        for (Long teamId : teamIdList) {
            Team team = teamMapper.selectById(teamId);
            TeamUserVo teamUserVo = new TeamUserVo();
            BeanUtils.copyProperties(team, teamUserVo);
            teamUserVoList.add(teamUserVo);
        }
        final List<Long> teamUserVoIdList = teamUserVoList
                .stream()
                .map(TeamUserVo::getId)
                .collect(Collectors.toList());
        // 2、判断用户是否已经加入队伍（前端判断 "加入队伍" 显隐）
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamUserVoIdList);
            // 已加入的队伍列表
            userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍id集合
            Set<Long> hasJoinTeamIdSet = userTeamList
                    .stream()
                    .map(UserTeam::getTeamId)
                    .collect(Collectors.toSet());
            teamUserVoList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e){}
        // 查询每个队伍的已加入用户数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamUserVoIdList);
        userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 一条或多条用户队伍列表（即该队伍已加入用户数）
        Map<Long, List<UserTeam>> groupByTeamIdUserTeamMap = userTeamList
                .stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 依次获得并赋值
        teamUserVoList.forEach(team -> {
            int hasJoinNum = groupByTeamIdUserTeamMap
                    .getOrDefault(team.getId(), new ArrayList<>()).size();
            team.setHasJoinNum(hasJoinNum);
        });
        return ResultUtils.success(teamUserVoList);
    }
}
